package com.wfit.bankproject.controller;

import com.wfit.bankproject.entity.JsonResult;
import com.wfit.bankproject.entity.User;
import com.wfit.bankproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;



@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService service;
    /**
     *
     * @param user
     * 新增用户
     */
    @PostMapping
    public JsonResult add(@RequestBody User user){
        boolean save = service.save(user);
        if(save)
        {
            return JsonResult.ok();
        }
        else
            return JsonResult.failure(500,"添加数据失败");
    }

    /**
     *
     * @param entity
     * 更新数据
     */
    @PutMapping
    public JsonResult update(@RequestBody User entity){
        if (entity.getId()==null){
            return JsonResult.failure(400,"Id值不能为空");
        }

        boolean b = service.updateById(entity);
        if (b){
            return JsonResult.ok();
        }
        return  JsonResult.failure(500,"更新失败");
    }

    /**
     *
     * @param id
     * 查询用户
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('user')")
    public JsonResult getById(@PathVariable Long id){
        User entity = service.getById(id);
        return  JsonResult.ok(entity);
    }

    /**
     *
     * @param id
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public JsonResult delbyId(@PathVariable Long id){
        boolean b = service.removeById(id);
        if (b){
            return JsonResult.ok();
        }
        return JsonResult.failure(300,"删除失败");
    }
}